package code.framework.android.service;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import android.content.Context;
import android.graphics.drawable.Drawable;

import com.google.inject.Singleton;

@Singleton
public class ResourceServiceImpl implements ResourceService {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * given a key and a R class, return the resource id
	 */
	public int getResId(Class<?> resourceIdClass, String id) {
		try {
			logger.trace("resourceIdClass = {}", resourceIdClass);
			Field field = resourceIdClass.getField(id);
			logger.trace("field = {}", field);
			return field.getInt(resourceIdClass);
		} catch (Exception e) {
			logger.error("", e);
			throw new RuntimeException(e);
		}
	}

	public Drawable getDrawable(Class<?> resourceIdClass, String id, Context c) {
		try {
			Integer resId = getResId(resourceIdClass, id);
			logger.trace("resId = {}", resId);
			return c.getResources().getDrawable(resId);
		} catch (Exception e) {
			logger.error("", e);
			throw new RuntimeException(e);
		}
	}

	public byte[] getBytes(URL url) throws IOException {
		InputStream inputStream = url.openStream();
		try {
			int size = inputStream.available();
			// System.out.println("size = "+size);
			if (size == 0) {
				size = BUFFER_SIZE;
			}
			byte[] buffer = new byte[size];
			byte[] result = null;
			int read = 0;
			while ((read = inputStream.read(buffer)) > 0) {
				// System.out.println("read = "+read);
				byte[] tempBytes = new byte[read];
				System.arraycopy(buffer, 0, tempBytes, 0, read);
				if (result == null) {
					result = new byte[read];
					// System.out.println("result.length = "+result.length);
					System.arraycopy(tempBytes, 0, result, 0, read);
				} else {
					// swap original bytes first
					int orignal = result.length;
					byte[] swapBytes = new byte[orignal];
					System.arraycopy(result, 0, swapBytes, 0, orignal);
					result = new byte[result.length + read];
					System.arraycopy(swapBytes, 0, result, 0, orignal);
					// copy new byte now
					System.arraycopy(tempBytes, orignal, result, orignal, read);
				}
			}
			return result;
		} finally {
			if (inputStream != null) {
				inputStream.close();
			}
		}
	}

}
